﻿
@{
    ViewData["Title"] = "Update";
    Layout = null;
}


<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="~/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />

</head>
<body>
    <!-- 给容器追加 class="layui-form-pane"，即可显示为方框风格 -->
    <form class="layui-form layui-form-pane" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">采购单号：</label>
            <div class="layui-input-block">
                <input type="text" name="ProcurementCode" id="ProcurementCode" placeholder="可不填写,自动生成" autocomplete="off" class="layui-input">
            </div>

        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">单据类型</label>
            <div class="layui-input-block">
                <select name="DocumentType" id="DocumentType" lay-filter="danju">
                    <option value="">请选择入库类别</option>
                    <option value="采购收货入库">采购收货入库</option>
                    <option value="销售退货入库">销售退货入库</option>
                    <option value="生产产品入库">生产产品入库</option>
                    <option value="领用退还入库">领用退还入库</option>
                    <option value="借货入库">借货入库</option>
                    <option value="借出还入">借出还入</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">关联销售单号：</label>
            <div class="layui-input-block">
                <input type="text" name="SaleCode" id="SaleCode" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">供应商名：</label>
            <div class="layui-input-block">
                <input type="text" name="SupplierName" id="SupplierName" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">客户名称：</label>
            <div class="layui-input-block">
                <input type="text" name="ClientName" id="ClientName" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">联系人</label>
                <div class="layui-input-inline layui-input-wrap">
                    <input type="tel" name="Contact" id="Contact" lay-verify="required|phone" autocomplete="off" lay-reqtext="请填写手机号" lay-affix="clear" class="layui-input demo-phone">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">电话：</label>
            <div class="layui-input-block">
                <input type="text" name="Phone" id="Phone" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">收获日</label>
                <div class="layui-input-inline layui-input-wrap">
                    <div class="layui-input-prefix">
                        <i class="layui-icon layui-icon-date"></i>
                    </div>
                    <input type="text" name="ReceivingDate" id="ReceivingDate" lay-verify="date" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">采购员</label>
            <div class="layui-input-block">
                <input type="text" name="Buyer" id="Buyer" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">采购时间</label>
                <div class="layui-input-inline">
                    <input type="text" class="layui-input" name="ProcurementDate" id="ProcurementDate" placeholder="yyyy-MM-dd HH:mm:ss">
                </div>
            </div>
        </div>
        <h2 style="margin-left:30px;float:left">产品信息</h2>
        <button style="float:right;margin-right:40px" type="button" class="layui-btn layui-btn-normal layui-btn-radius" onclick="toprocurement()">选择产品</button>
        <br />
        <table class="layui-hide" id="ID-table-demo-data"></table>
        <br />
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" type="button" lay-submit lay-filter="btnUpdate">确认</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
    <script src="~/layui-v2.5.6/layui/layui.js"></script>
    <script src="~/libs/jquery/jquery.js"></script>
    <script>
        layui.use(['form', 'laydate', 'table'], function () {
            var form = layui.form;
            var layer = layui.layer;
            var $ = layui.$;
            var laydate = layui.laydate;
            var table = layui.table;


            // 日期选择器
            laydate.render({
                elem: '#ReceivingDate',
                //format: 'yyyy年MM月dd日'
            });

            // 日期时间选择器
            laydate.render({
                elem: '#ProcurementDate',
                type: 'datetime',
                fullPanel: true, // 2.8+
                //format: 'yyyy年MM月dd日'
            });

            var procurementcode = "";
            var supplier = "";

            // 已知数据渲染
            querylist = function () {
                var productstable = JSON.parse(sessionStorage.getItem("products"));
                console.log(productstable);
                table.render({
                    elem: '#ID-table-demo-data',
                    data: productstable,
                    cols: [[ //标题栏
                        , { field: 'ProductName', title: '产品名称', width: 150 }
                        , { field: 'ProductCode', title: '产品编码', width: 150 }
                        , { field: 'ProductSpecification', title: '规格', width: 150 }
                        , { field: 'StorageUnit', title: '单位', width: 150 }
                        , { field: 'UnitPrice', title: '单价', width: 150 }
                        , {
                            field: 'Quantity', title: '数量', width: 100, templet: function (res) {
                                return '<input type="number" class="layui-input quantity-input" value="' + res.Quantity + '" style="width: 50px;">';
                            }
                        }
                        , {
                            field: 'SumMoney', title: '总额', width: 100, templet: function (res) {
                                var quantity = res.Quantity || 0; // 如果 Quantity 不存在，则默认值为 0
                                var unitPrice = res.UnitPrice || 0; // 如果 UnitPrice 不存在，则默认值为 0
                                return '<span class="sum-money">' + (quantity * unitPrice).toFixed(2) + '</span>'; // 确保结果保留两位小数
                            }
                        }
                    ]],
                    //skin: 'line', // 表格风格
                    //even: true,
                    //page: true, // 是否显示分页
                    //limits: [5, 10, 15],
                    //limit: 5 // 每页默认显示的数量
                    done: function (res) {
                        // 初始化完成后绑定事件
                        $(document).off('input', '.quantity-input').on('input', '.quantity-input', function () {
                            var $this = $(this);
                            var sumMoney = $this.val() * parseFloat($this.closest('tr').find('td[data-field="UnitPrice"]').text());
                            $this.closest('tr').find('.sum-money').text(sumMoney.toFixed(2));
                        });
                    }

                });
            }
            // table.reload('#ID-table-demo-data', {
            //     data: productstable
            // })
            querylist();

            var updateclient = JSON.parse(localStorage.getItem("updateProcurement"));
            console.log(updateclient);
            $("[name=ProcurementCode]").val(updateclient.ProcurementCode)
            //$("[name=DocumentType]").val(updateclient.DocumentType)
            $(`[name=DocumentType][value=${updateclient.DocumentType}]`).prop("checked", true);
            $("[name=SaleCode]").val(updateclient.SaleCode)
            $("[name=SupplierName]").val(updateclient.SupplierName)
            // $("[name=Type]").val(updateclient.Type)
            // form.render('select'); // 仅渲染 select 元素
            $(`[name=ClientName][value=${updateclient.ClientName}]`).prop("checked", true);
            $("[name=Contact]").val(updateclient.Contact)
            $("[name=Phone]").val(updateclient.Phone)
            $("[name=ReceivingDate]").val(updateclient.ReceivingDate)
            $("[name=Buyer]").val(updateclient.Buyer)
            $("[name=ProcurementDate]").val(updateclient.ProcurementDate)
            
            // 提交事件
            form.on('submit(btnUpdate)', function (data) {
                data = data.field;
                var ProcurementDetailLists = sessionStorage.getItem("products");
                var ProcurementDetailList = JSON.parse(ProcurementDetailLists);
                console.log(ProcurementDetailList); // 在控制台输出选中的产品信息
                var results = [];
                // 遍历选中的产品
                ProcurementDetailList.forEach((product, index) => { // 使用第二个参数获取当前索引
                    console.log('Index:', index, 'ProductCode:', product.ProductCode);
                    // 获取当前表格行中数量输入框的值
                    var quantityInput = $('tr[data-index="' + index + '"] .quantity-input'); // 使用正确的 index
                    console.log('Quantity Input Element:', quantityInput); // 检查是否成功获取到输入框

                    // 获取输入框的值
                    var quantity = parseFloat(quantityInput.val()) || 0; // 如果输入框为空，则默认值为 0
                    console.log('Quantity:', quantity); // 输出获取到的数量
                    // 将结果添加到数组
                    results.push({
                        Ids: product.ProductCode,
                        Nums: quantity,
                    });
                });
                console.log(results);
                updateclient.purchasedetails = results;
                console.log(updateclient)
                updateclient.ProcurementCode = data.ProcurementCode;
                updateclient.DocumentType = data.DocumentType;
                updateclient.SaleCode = data.SaleCode;
                updateclient.SupplierName = data.SupplierName;
                updateclient.ClientName = data.ClientName;
                updateclient.Contact = data.Contact;
                updateclient.Phone = data.Phone;
                updateclient.ReceivingDate = data.ReceivingDate;
                updateclient.Buyer = data.Buyer;
                updateclient.ProcurementDate = data.ProcurementDate;
                if (updateclient.ProcurementCode === "") {
                    procurementrandom();
                    supplierrandom();
                    updateclient.ProcurementCode = procurementcode;
                    updateclient.SupplierCode = supplier;
                    console.log(updateclient)
                    $.post("/Procurement/UpdateProcurement", updateclient,
                        res => {
                            if (res) {
                                layer.msg('修改采购成功', {
                                    icon: 1,
                                    time: 1000
                                }, function () {
                                    var index = parent.layer.getFrameIndex(window.name);
                                    parent.layer.close(index);
                                    window.location = '/Procurement/Show';
                                });
                            }
                            else {
                                layer.msg('修改采购失败！', {
                                    icon: 1,
                                    time: 1000
                                });
                            }
                        }
                    )
                } else {
                    supplierrandom();
                    updateclient.SupplierCode = supplier;
                    console.log(updateclient)
                    $.post("/Procurement/UpdateProcurement", updateclient,
                        res => {
                            if (res) {
                                layer.msg('修改采购成功', {
                                    icon: 1,
                                    time: 1000
                                }, function () {
                                    var index = parent.layer.getFrameIndex(window.name);
                                    parent.layer.close(index);
                                    window.location = '/Procurement/Show';
                                });
                            }
                            else {
                                layer.msg('修改采购失败！', {
                                    icon: 1,
                                    time: 1000
                                });
                            }
                        }
                    )
                }
                
            });
            var procurementrandom = function () {
                var index = "1234567890";
                var num = "";
                for (var i = 0; i < 7; i++) { // 循环10次
                    // 生成一个五位数的随机数
                    var randomFiveDigitNumber = Math.floor(Math.random() * index.length);
                    num += index[randomFiveDigitNumber]
                }
                var codes = "CG" + num;
                procurementcode = codes;
                return false;
            }
            var supplierrandom = function () {
                var index = "1234567890";
                var num = "";
                for (var i = 0; i < 5; i++) { // 循环10次
                    // 生成一个五位数的随机数
                    var randomFiveDigitNumber = Math.floor(Math.random() * index.length);
                    num += index[randomFiveDigitNumber]
                }
                var codes = "GX" + num;
                supplier = codes;
                return false;
            }
        });
        function toprocurement() {
            layer.open({
                type: 2, // page 层类型
                area: ['80%', '80%'],
                title: '选择产品',
                shade: 0.6, // 遮罩透明度
                shadeClose: true, // 点击遮罩区域，关闭弹层
                maxmin: true, // 允许全屏最小化
                anim: 0, // 0-6 的动画形式，-1 不开启
                content: '/Procurement/ChangeProducts',//'<div style="padding: 32px;">一个普通的页面层，传入了自定义的 HTML</div>'
                end: function () {
                    querylist();
                }
            });
        }
    </script>
</body>
</html>

